<?php

class AuthController extends Controller
{

	/**
     * 过滤器
	 * @return 返回值是一个存放过滤器的数组
	 */
	public function filters()
	{
		return array(
            'accessAuth',//自定义授权方式
			//'accessControl', //默认授权方式
			'postOnly + delete',//删除操作只支持post请求
		);
	}
    /**
     * 自定义权限验证规则
     * @param type $filterChain
     * @throws CHttpException
     */
    public function filterAccessAuth($filterChain) {  
        if(Yii::app()->user->getIsGuest()) {  
            echo '<script>top.location.href="'.Yii::app()->user->returnUrl.'";</script>';
            exit;
        } else if(!Yii::app()->user->getIsGuest() && !in_array($this->getAction()->getId(), $this->authlessActions())){
            throw new CHttpException(403,'无权访问此页面');
        }
        $filterChain->run();  
    }  
    /**
     * 页面白名单
     * @return type
     */
    public function authlessActions() {  
        return array(
            'admin','create','update','delete'
		); 
    }
    
    /**
     * 权限管理
     */
    public function actionAdmin(){
        $model=new Authitem_new('search');
	$model->unsetAttributes();  //清空并初始化
        
        $_GET['Authitem_new']=Array ( "type" => "2");        
        $model->attributes=$_GET['Authitem_new'];
        $this->render('admin',array(
            'model'=>$model,
            'data'=>$model->search(),
	));
    }
        
        /**
	 * 角色授权修改页面
	 * 如果修改成功，跳转到查看页面
	 * @param integer $id 
	 */
	public function actionUpdate($name){                
                $model=  Authitem_new::model()->find("name = '".$name."'");
                
                $Authmodule=new Authmodule_new;
                $result=$Authmodule->findAll("1=1");
                $res1=array();
                 for($temp=0;$temp < count($result);$temp++){
                    $key=$result[$temp]["id"];
                    $value=$result[$temp]["modulename"];
                    $res1["$key"]=$value;
                }
                $res2=array("1"=>"浏览","2"=>"编辑","3"=>"导入/导出");
                                
                $checks1=array();
                $checks2=array();
                //查询任务
                $Authitemchild_new=new Authitemchild_new();
                $Authitem_new=new Authitem_new();
                
                $result=$Authitemchild_new->findAll("parent = '".$name."'");
                $task=$result[0]["child"];
                //查询任务对应action
                $result=$Authitemchild_new->findAll("parent = '".$task."'");
                $condition="";
                for($temp=0;$temp < count($result);$temp++){
                    $condition=$condition.","."'".$result[$temp]["child"]."'" ;                   
                }
                $condition=substr($condition,1);
                if($condition!=""){
                    $result=$Authitem_new->findAll(" type=0 and name in (".$condition.")");
                }
                
                
                //查询action对应模块
                //过滤出选中的模块和可以操作的权限
                for($temp=0;$temp < count($result);$temp++){
                    $mid=$result[$temp]["modelid"];
                    $opid=$result[$temp]["opertype"];
                    $checks1["$mid"]=$mid;
                    $checks2["$opid"]=$opid;
                }
                $res3="";
                $res4="";
                $count=0;
                foreach($res1 as $key=>$value) {
                    $flag='';
                    if(array_key_exists($key,$checks1)){
                        $flag=' checked="check"';
                    }
                    $res3=$res3.' <input id="Authitem_new_checks1_"'.$count.' value="'.$key.'" type="checkbox" name="Authitem_new[checks1][]" '.$flag.'> 
                    <label for="Authitem_new_checks1_'.$count.'">'.$value.'</label>';
                    $count++;
                }
                
                $count=0;
                foreach($res2 as $key=>$value) {
                    $flag='';
                    if(array_key_exists($key,$checks2)){
                        $flag=' checked="check"';
                    }
                    $res4=$res4.' <input id="Authitem_new_checks2_'.$count.'" value="'.$key.'" type="checkbox" name="Authitem_new[checks2][]" '.$flag.'> 
                    <label for="Authitem_new_checks2_'.$count.'">'.$value.'</label>';
                    $count++;
                }
                
		if(isset($_POST['Authitem_new'])){
                    $model->attributes=$_POST['Authitem_new'];
                    $name=$model->name;
                    
                    $Authitemchild_new=new Authitemchild_new();
                    $result=$Authitemchild_new->findAll("parent = '".$name."'");
                    $task=$result[0]["child"];
                    //关联任务和action
                    Authitemchild_new::model()->deleteAll("parent='".$task."'");
//                    //关联角色和任务
//                    $Authitemchild_new::model()->deleteAll("parent = '".$name."'");
//                    //新建任务
//                    $Authitem_new=new Authitem_new();
//                    $Authitem_new::model()->deleteAll("type = 1 and name = '".$task."'");
//                    //新建角色
//                    $res= $Authitem_new::model()->deleteAll("type = 2 and name = '".$name."'");
                        
//                    //新建角色
//                    $role=new Authitem_new();
//                    $role->name=$name;
//                    $role->type=2;
//                    $role->save();
//                    //新建任务
//                    $task=new Authitem_new();
//                    $task->name=$name."_task";
//                    $task->type=1;
//                    $task->save();
//                    //关联角色和任务
//                    $relation=new Authitemchild_new();
//                    $relation->parent=$name;
//                    $relation->child=$name."_task";
//                    $relation->save();
                    //根据选择的模块找到对应的action
                    $Authitem_new=new Authitem_new;
                    $condition="";
                    $checks1="";
                    foreach ($_POST['Authitem_new']["checks1"] as $temp){
                        $checks1=$checks1.",".$temp;
                    }
                    $checks1=substr($checks1,1);
                    $condition=" and modelid in (".$checks1.")";
                    
                    $checkList='';
                    foreach ($_POST['Authitem_new']["checks2"] as $temp){
                            $checkList.=$temp.',';
                    }
                    
                    $checkList=substr($checkList,0,strlen($checkList)-1);
                    $condition.=' and opertype in('.$checkList.') ';
      
//                    if($checks2==1){
//                        $condition=$condition." and opertype = 1";
//                    }else if($checks2==2||$checks2==3){
//                        $condition=$condition." and (opertype = 1 or opertype = 2)";
//                    }
                    $result=$Authitem_new->findAll(" type=0 ".$condition);
                    
                    //关联任务和action
                    for($temp=0;$temp < count($result);$temp++){
                        $relation=new Authitemchild_new();
                        $relation->parent=$name."_task";
                        $relation->child=$result[$temp]["name"];
                        $relation->save();
                    }
                    Yii::app()->user->setFlash('success','操作成功！');
                    $this->redirect(array('Auth/admin'));
		}

		$this->render('update',array(
			'model'=>$model,
                        'model_check1'=>$res3,
                        'model_check2'=>$res4,
		));
	}
        
        /**
	 * 添加页面
	 * 如果添加成功，跳转到查看页面
	 */
	public function actionCreate(){
		$model=new Authitem_new;
                
                
                $Authmodule=new Authmodule_new;
                $result=$Authmodule->findAll("1=1");
                 for($temp=0;$temp < count($result);$temp++){
                    $key=$result[$temp]["id"];
                    $value=$result[$temp]["modulename"];
                    $res1["$key"]=$value;
                }
                $res2=array("1"=>"浏览","2"=>"编辑","3"=>"导入/导出");
                $model->checks1="";
                $model->checks2="";

                if(isset($_POST['Authitem_new'])){
                    $transaction = Yii::app()->db->beginTransaction(); //创建事务
                    $model->attributes=$_POST['Authitem_new'];
                    $model->validate();
   
                    //新建角色
                    $role=new Authitem_new();
                    $role->name=$_POST['Authitem_new']["name"];
                    $role->type=2;
                    if(!$role->save()){
                        $transaction->rollback(); //回滚事务
                    }else{
                        //新建任务
                        $task=new Authitem_new();
                        $task->name=$_POST['Authitem_new']["name"]."_task";
                        $task->type=1;
                        if(!$task->save()){
                            $transaction->rollback(); //回滚事务
                        }else{
                            //关联角色和任务
                            $relation=new Authitemchild_new();
                            $relation->parent=$_POST['Authitem_new']["name"];
                            $relation->child=$_POST['Authitem_new']["name"]."_task";
                            if(!$relation->save()){
                                $transaction->rollback(); //回滚事务
                            }else{
                                //根据选择的模块找到对应的action
                                $Authitem_new=new Authitem_new;
                                $condition="";
                                $checks1="";
                                foreach ($_POST['Authitem_new']["checks1"] as $temp){
                                    $checks1=$checks1.",".$temp;
                                }
                                $checks1=substr($checks1,1);
                                $condition=" and modelid in (".$checks1.")";
                                
                                
                                 $checkList='';
                                foreach ($_POST['Authitem_new']["checks2"] as $temp){
                                        $checkList.=$temp.',';
                                }

                                $checkList=substr($checkList,0,strlen($checkList)-1);
                                $condition.=' and opertype in('.$checkList.') ';

//                                $checks2=0;
//                                foreach ($_POST['Authitem_new']["checks2"] as $temp){
//                                    if($temp>$checks2){
//                                        $checks2=$temp;
//                                    }
//                                }
//                                if($checks2==1){
//                                    $condition=$condition." and opertype = 1";
//                                }else if($checks2==2||$checks2==3){
//                                    $condition=$condition." and (opertype = 1 or opertype = 2)";
//                                }
                                $result=$Authitem_new->findAll(" type=0 ".$condition);

                                //关联任务和action
                                for($temp=0;$temp < count($result);$temp++){
                                    $relation=new Authitemchild_new();
                                    $relation->parent=$_POST['Authitem_new']["name"]."_task";
                                    $relation->child=$result[$temp]["name"];
                                    if(!$relation->save()){
                                        $transaction->rollback(); //回滚事务
                                    }
                                }

                                $transaction->commit(); //提交事务
                                Yii::app()->user->setFlash('success','操作成功！');
                                $this->redirect(array('Auth/admin'));
                            }
                        }
                    }
                }
                
		$this->render('create',array(
			'model'=>$model,
                        'model_check1'=>$res1,
                        'model_check2'=>$res2,
		));
	}

        
/**
	 * 删除功能
	 * 一般只接受post方式的异步提交
	 * @param integer $id 
	 */
	public function actionDelete($id){
            $transaction = Yii::app()->db->beginTransaction(); //创建事务
            //$id是角色name
            if(Yii::app()->request->isAjaxRequest && isset($_POST['id'])){
                $ids=$_POST['id'];
                foreach ($ids as $id){
                    $Authitemchild_new=new Authitemchild_new();
                    $result=$Authitemchild_new->findAll("parent = '".$id."'");
                    $task=$result[0]["child"];
                   //关联任务和action
                   Authitemchild_new::model()->deleteAll("parent='".$task."'");
                    //关联角色和任务
                    $Authitemchild_new::model()->deleteAll("parent = '".$id."'");
                   //新建任务
                    $Authitem_new=new Authitem_new();
                   $Authitem_new::model()->deleteAll("type = 1 and name = '".$task."'");
                   //新建角色
                   $res= $Authitem_new::model()->deleteAll("type = 2 and name = '".$id."'");
               }
               $transaction->commit(); //提交事务
//                $res=  Authitem_new::model()->deleteAll($criteria);
//                //输出json结果
                echo CJSON::encode(array('result'=>$res));
            }else{
                $this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('admin'));
            } 
	}
        
	/**
	 * Returns the data model based on the primary key given in the GET variable.
	 * If the data model is not found, an HTTP exception will be raised.
	 * @param integer $id the ID of the model to be loaded
	 * @return Sms the loaded model
	 * @throws CHttpException
	 */
	public function loadModel($id)
	{
		$model=Sms::model()->findByPk($id);
		if($model===null)
			throw new CHttpException(404,'The requested page does not exist.');
		return $model;
	}

	/**
	 * Performs the AJAX validation.
	 * @param Sms $model the model to be validated
	 */
	protected function performAjaxValidation($model)
	{
		if(isset($_POST['ajax']) && $_POST['ajax']==='Authitem_new-form')
		{

			echo CActiveForm::validate($model);
			Yii::app()->end();
		}
	}
	
}
